﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using DevExpress.Xpo.Metadata;

namespace TransLogger.Module
{
    public class FileLinkImageValueConverter : ImageValueConverter
    {
        public override Type StorageType
        {
            get
            {
                return typeof(string);
            }
        }

        public override object ConvertFromStorageType(object value)
        {
            if (value == null)
            {
                return null;
            }
            var path = value.ToString();
            if (File.Exists(path))
            {
                return Util.LoadFrom(path);
            }

            return null;
        }

        public override object ConvertToStorageType(object value)
        {
            if (value == null)
            {
                return null;
            }

            var dirName = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            var relativePath = string.Format(@"{0:yyyy-MM-dd}\{1}.jpg",
                DateTime.Now, Guid.NewGuid());
            var path = Path.Combine(dirName, "Vehimg", relativePath);
            var dir = Path.GetDirectoryName(path);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            var img = (Image)value;
            img.Save(path);
            return path;
        }
    }
}
